/**
 * 模板管理器组件
 * 提供模板管理、编辑、删除等功能
 */

import React, { useState, useEffect, useMemo } from 'react'
import {
  Modal,
  Table,
  Button,
  Input,
  Select,
  Space,
  Tag,
  Popconfirm,
  message,
  Card,
  Row,
  Col,
  Statistic,
  Tabs,
  Upload,
  Typography,
  Divider
} from 'antd'
import {
  EditOutlined,
  DeleteOutlined,
  DownloadOutlined,
  UploadOutlined,
  PlusOutlined,
  SearchOutlined,
  FileTextOutlined
} from '@ant-design/icons'
import type { ColumnsType } from 'antd/es/table'
import type { UploadProps } from 'antd/es/upload'
import {
  DocumentTemplate,
  TemplateCategory,
  TemplateLabelType,
  TemplateStats,
  TemplateFilters
} from '../../../types/template'
import { templateService } from '../../../services/templates'
import { getTemplateCategoryInfo, getTemplateTypeInfo } from '../../../services/templates/builtInTemplates'
import { TemplateEditor } from '../TemplateEditor'

const { Search } = Input
const { Option } = Select
const { TabPane } = Tabs
const { Text } = Typography

interface TemplateManagerProps {
  visible: boolean
  onClose: () => void
  onTemplateSelect?: (template: DocumentTemplate) => void
}

/**
 * 模板管理器主组件
 */
export const TemplateManager: React.FC<TemplateManagerProps> = ({
  visible,
  onClose,
  onTemplateSelect
}) => {
  const [loading, setLoading] = useState(false)
  const [templates, setTemplates] = useState<DocumentTemplate[]>([])
  const [stats, setStats] = useState<TemplateStats | null>(null)
  const [searchQuery, setSearchQuery] = useState('')
  const [selectedCategory, setSelectedCategory] = useState<TemplateCategory | undefined>()
  const [selectedType, setSelectedType] = useState<TemplateLabelType | undefined>()
  const [activeTab, setActiveTab] = useState('list')
  
  // 编辑相关状态
  const [editingTemplate, setEditingTemplate] = useState<DocumentTemplate | null>(null)
  const [editorVisible, setEditorVisible] = useState(false)
  const [createMode, setCreateMode] = useState(false)

  const categoryInfos = useMemo(() => getTemplateCategoryInfo(), [])
  const typeInfos = useMemo(() => getTemplateTypeInfo(), [])

  // 加载模板列表
  const loadTemplates = async () => {
    setLoading(true)
    try {
      const filters: TemplateFilters = {}
      
      if (selectedCategory) {
        filters.category = [selectedCategory]
      }
      
      if (selectedType) {
        filters.type = [selectedType]
      }

      const result = await templateService.searchTemplates(searchQuery, filters)
      
      if (result.success) {
        setTemplates(result.data.templates)
      } else {
        message.error(`加载模板失败: ${result.error}`)
      }
    } catch (error) {
      console.error('[模板管理器] 加载模板失败:', error)
      message.error('加载模板失败')
    } finally {
      setLoading(false)
    }
  }

  // 加载统计信息
  const loadStats = async () => {
    try {
      const result = await templateService.getTemplateStats()
      if (result.success) {
        setStats(result.data)
      }
    } catch (error) {
      console.error('[模板管理器] 加载统计信息失败:', error)
    }
  }

  // 初始化
  useEffect(() => {
    if (visible) {
      loadTemplates()
      loadStats()
    }
  }, [visible, searchQuery, selectedCategory, selectedType])

  // 删除模板
  const handleDeleteTemplate = async (template: DocumentTemplate) => {
    try {
      const result = await templateService.deleteTemplate(template.id)
      if (result.success) {
        message.success('模板删除成功')
        loadTemplates()
        loadStats()
      } else {
        message.error(`删除失败: ${result.error}`)
      }
    } catch (error) {
      console.error('[模板管理器] 删除模板失败:', error)
      message.error('删除模板失败')
    }
  }

  // 导出模板
  const handleExportTemplate = async (template: DocumentTemplate) => {
    try {
      const result = await templateService.exportTemplate(template.id)
      if (result.success) {
        // 创建下载链接
        const blob = new Blob([result.data], { type: 'application/json' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${template.name}.json`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        
        message.success('模板导出成功')
      } else {
        message.error(`导出失败: ${result.error}`)
      }
    } catch (error) {
      console.error('[模板管理器] 导出模板失败:', error)
      message.error('导出模板失败')
    }
  }

  // 批量导出模板
  const handleBatchExport = async () => {
    try {
      const templateIds = templates.map(t => t.id)
      const result = await templateService.exportTemplates(templateIds)
      
      if (result.success) {
        const blob = new Blob([result.data], { type: 'application/json' })
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `templates-${new Date().getTime()}.json`
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(url)
        
        message.success(`成功导出 ${templateIds.length} 个模板`)
      } else {
        message.error(`导出失败: ${result.error}`)
      }
    } catch (error) {
      console.error('[模板管理器] 批量导出失败:', error)
      message.error('批量导出失败')
    }
  }

  // 导入模板
  const handleImportTemplates: UploadProps['beforeUpload'] = (file) => {
    const reader = new FileReader()
    reader.onload = async (e) => {
      try {
        const content = e.target?.result as string
        const result = await templateService.importTemplates(content)
        
        if (result.success && result.data.success) {
          message.success(`成功导入 ${result.data.templateIds.length} 个模板`)
          loadTemplates()
          loadStats()
        } else {
          const errors = result.data.errors || [result.error || '导入失败']
          message.error(`导入失败: ${errors.join(', ')}`)
        }
      } catch (error) {
        console.error('[模板管理器] 导入模板失败:', error)
        message.error('导入模板失败')
      }
    }
    reader.readAsText(file)
    return false // 阻止自动上传
  }

  // 编辑模板
  const handleEditTemplate = (template: DocumentTemplate) => {
    setEditingTemplate(template)
    setCreateMode(false)
    setEditorVisible(true)
  }

  // 创建新模板
  const handleCreateTemplate = () => {
    setEditingTemplate(null)
    setCreateMode(true)
    setEditorVisible(true)
  }

  // 编辑器保存成功回调
  const handleEditorSave = () => {
    setEditorVisible(false)
    setEditingTemplate(null)
    setCreateMode(false)
    loadTemplates()
    loadStats()
  }

  // 表格列定义
  const columns: ColumnsType<DocumentTemplate> = [
    {
      title: '模板名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
      render: (name: string, record: DocumentTemplate) => (
        <Space>
          <FileTextOutlined />
          <span>{name}</span>
          {record.isBuiltIn && (
            <Tag color="green" size="small">内置</Tag>
          )}
        </Space>
      )
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category: TemplateCategory) => {
        const info = categoryInfos.find(c => c.category === category)
        return (
          <Tag color="blue">
            <span style={{ marginRight: 4 }}>{info?.icon}</span>
            {info?.name}
          </Tag>
        )
      },
      filters: categoryInfos.map(info => ({
        text: `${info.icon} ${info.name}`,
        value: info.category
      })),
      onFilter: (value, record) => record.category === value
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 120,
      render: (type: TemplateLabelType) => {
        const info = typeInfos.find(t => t.type === type)
        return <Tag color={info?.color}>{info?.name}</Tag>
      },
      filters: typeInfos.map(info => ({
        text: info.name,
        value: info.type
      })),
      onFilter: (value, record) => record.type === value
    },
    {
      title: '难度',
      dataIndex: ['metadata', 'difficulty'],
      key: 'difficulty',
      width: 80,
      render: (difficulty: string) => (
        <Tag color={
          difficulty === 'easy' ? 'green' :
          difficulty === 'medium' ? 'orange' : 'red'
        }>
          {difficulty === 'easy' ? '简单' :
           difficulty === 'medium' ? '中等' : '困难'}
        </Tag>
      )
    },
    {
      title: '使用次数',
      dataIndex: 'usageCount',
      key: 'usageCount',
      width: 100,
      sorter: (a, b) => a.usageCount - b.usageCount
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (date: Date) => date.toLocaleDateString(),
      sorter: (a, b) => a.createdAt.getTime() - b.createdAt.getTime()
    },
    {
      title: '操作',
      key: 'actions',
      width: 180,
      render: (_, record: DocumentTemplate) => (
        <Space>
          {onTemplateSelect && (
            <Button 
              type="link" 
              size="small"
              onClick={() => onTemplateSelect(record)}
            >
              选择
            </Button>
          )}
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEditTemplate(record)}
            disabled={record.isBuiltIn}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<DownloadOutlined />}
            onClick={() => handleExportTemplate(record)}
          >
            导出
          </Button>
          <Popconfirm
            title="确定要删除这个模板吗？"
            onConfirm={() => handleDeleteTemplate(record)}
            disabled={record.isBuiltIn}
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
              disabled={record.isBuiltIn}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ]

  return (
    <>
      <Modal
        title="模板管理"
        visible={visible}
        onCancel={onClose}
        footer={null}
        width={1400}
        style={{ top: 20 }}
        destroyOnClose
      >
        <Tabs activeKey={activeTab} onChange={setActiveTab}>
          <TabPane tab="模板列表" key="list">
            <div style={{ marginBottom: 16 }}>
              <Row gutter={[16, 16]}>
                <Col span={8}>
                  <Search
                    placeholder="搜索模板"
                    allowClear
                    onSearch={setSearchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                  />
                </Col>
                <Col span={5}>
                  <Select
                    placeholder="选择分类"
                    allowClear
                    style={{ width: '100%' }}
                    value={selectedCategory}
                    onChange={setSelectedCategory}
                  >
                    {categoryInfos.map(info => (
                      <Option key={info.category} value={info.category}>
                        <span style={{ marginRight: 8 }}>{info.icon}</span>
                        {info.name}
                      </Option>
                    ))}
                  </Select>
                </Col>
                <Col span={5}>
                  <Select
                    placeholder="选择类型"
                    allowClear
                    style={{ width: '100%' }}
                    value={selectedType}
                    onChange={setSelectedType}
                  >
                    {typeInfos.map(info => (
                      <Option key={info.type} value={info.type}>
                        {info.name}
                      </Option>
                    ))}
                  </Select>
                </Col>
                <Col span={6}>
                  <Space>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleCreateTemplate}
                    >
                      新建模板
                    </Button>
                    <Upload beforeUpload={handleImportTemplates} showUploadList={false}>
                      <Button icon={<UploadOutlined />}>导入</Button>
                    </Upload>
                    <Button
                      icon={<DownloadOutlined />}
                      onClick={handleBatchExport}
                      disabled={templates.length === 0}
                    >
                      批量导出
                    </Button>
                  </Space>
                </Col>
              </Row>
            </div>

            <Table
              columns={columns}
              dataSource={templates}
              rowKey="id"
              loading={loading}
              pagination={{
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 个模板`
              }}
              scroll={{ x: 1200 }}
            />
          </TabPane>

          <TabPane tab="统计信息" key="stats">
            {stats && (
              <div>
                <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
                  <Col span={6}>
                    <Card>
                      <Statistic
                        title="总模板数"
                        value={stats.totalTemplates}
                        prefix={<FileTextOutlined />}
                      />
                    </Card>
                  </Col>
                  <Col span={6}>
                    <Card>
                      <Statistic
                        title="内置模板"
                        value={stats.builtInTemplates}
                        valueStyle={{ color: '#52c41a' }}
                      />
                    </Card>
                  </Col>
                  <Col span={6}>
                    <Card>
                      <Statistic
                        title="自定义模板"
                        value={stats.customTemplates}
                        valueStyle={{ color: '#1890ff' }}
                      />
                    </Card>
                  </Col>
                  <Col span={6}>
                    <Card>
                      <Statistic
                        title="总使用次数"
                        value={templates.reduce((sum, t) => sum + t.usageCount, 0)}
                        valueStyle={{ color: '#faad14' }}
                      />
                    </Card>
                  </Col>
                </Row>

                <Row gutter={16}>
                  <Col span={12}>
                    <Card title="分类统计" size="small">
                      {Object.entries(stats.categoryCounts).map(([category, count]) => {
                        const info = categoryInfos.find(c => c.category === category)
                        return (
                          <div key={category} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                            <span>
                              <span style={{ marginRight: 8 }}>{info?.icon}</span>
                              {info?.name}
                            </span>
                            <Text strong>{count}</Text>
                          </div>
                        )
                      })}
                    </Card>
                  </Col>
                  <Col span={12}>
                    <Card title="最常用模板" size="small">
                      {stats.mostUsedTemplates.slice(0, 5).map(template => (
                        <div key={template.id} style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                          <span>{template.name}</span>
                          <Text strong>{template.usageCount} 次</Text>
                        </div>
                      ))}
                    </Card>
                  </Col>
                </Row>
              </div>
            )}
          </TabPane>
        </Tabs>
      </Modal>

      <TemplateEditor
        visible={editorVisible}
        template={editingTemplate}
        isCreate={createMode}
        onSave={handleEditorSave}
        onCancel={() => setEditorVisible(false)}
      />
    </>
  )
}